/*
 * Copyright 2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.pajamas.starter.integration.spring.amqp;

import com.google.common.collect.Maps;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.pajamas.starter.core.util.VmUtils;
import org.pajamas.starter.integration.module.context.PajamasPropSrcConstants;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;

import java.util.Map;
import java.util.Objects;

import javax.annotation.Nonnull;

import lombok.RequiredArgsConstructor;

/**
 * bases on {@code RabbitTemplate}
 * receiving disabled, but more excellent for the sending
 *
 * @author william
 * @since 2024/5/25
 */
@RequiredArgsConstructor
public class PublishEndpoint {
    private final RabbitTemplate template;

    @Value("${spring.cloud.nacos.discovery.group:DEFAULT_GROUP}")
    private String groupId;
    @Value("${spring.cloud.nacos.discovery.service:}")
    private String serviceId;
    @Value("${spring.application.name:}")
    private String applicationName;
    @Value("${spring.cloud.nacos.discovery.cluster-name:DEFAULT}")
    private String clusterId;
    @Value("${" + PajamasPropSrcConstants.INSTANCE_ID + "}")
    private String instanceId;

    private static MessagePostProcessor applyMessagePostProcessor(Staging staging) {
        return message -> {
            if (staging.ttl != null) {
                message.getMessageProperties().setExpiration(staging.ttl.toString());
            }
            if (MapUtils.isNotEmpty(staging.headers)) {
                message.getMessageProperties().setHeaders(staging.headers);
            }
            return message;
        };
    }

    public Staging staging() {
        // set default attr
        return new Staging(this)
                .exchangeName(this.template.getExchange())
                .routingKey(this.template.getRoutingKey())
                .addHeader(Namings.HEADER_KEY_GROUP_ID, this.groupId)
                .addHeader(Namings.HEADER_KEY_SERVICE_ID, StringUtils.firstNonBlank(this.serviceId,
                        this.applicationName))
                .addHeader(Namings.HEADER_KEY_CLUSTER_ID, this.clusterId)
                .addHeader(Namings.HEADER_KEY_INSTANCE_ID, this.instanceId)
                .addHeader(Namings.HEADER_KEY_THREAD_NAME, VmUtils.getCurrentThreadName());
    }

    private void delegatedSend(@Nonnull Staging staging) {
        this.template.convertAndSend(
                staging.exchangeName,
                staging.routingKey,
                staging.payload,
                applyMessagePostProcessor(staging),
                null);
    }

    public static class Staging {
        private final PublishEndpoint endpoint;
        private final Map<String, Object> headers;
        private String exchangeName;
        private String routingKey;
        private Object payload;
        private Integer ttl;

        private Staging(@Nonnull PublishEndpoint endpoint) {
            this.endpoint = endpoint;
            this.headers = Maps.newHashMap();
        }

        public Staging exchangeName(String exchangeName) {
            this.exchangeName = exchangeName;
            return this;
        }

        public Staging routingKey(String routingKey) {
            this.routingKey = routingKey;
            return this;
        }

        public Staging payload(Object payload) {
            this.payload = payload;
            return this;
        }

        public Staging ttl(int ttl) {
            this.ttl = ttl;
            return this;
        }

        @SuppressWarnings("UnusedReturnValue")
        public Staging addHeader(String key, Object value) {
            if (StringUtils.isNotBlank(key)) {
                this.headers.put(key, value);
            }
            return this;
        }

        public Staging addHeaders(Map<String, Object> headers) {
            if (MapUtils.isNotEmpty(headers)) {
                headers.entrySet()
                        .stream()
                        .filter(Objects::nonNull)
                        .forEach(entry -> this.addHeader(entry.getKey(), entry.getValue()));
            }
            return this;
        }

        public void send() {
            this.endpoint.delegatedSend(this);
        }
    }
}
